package 二分;

import java.util.ArrayList;

/**
 * @author 帅小伙
 * @date 2021/12/26
 * @description
 */
public class Demo03JZ53 {

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();

        list.add("a");
        list.add("a");
        list.add("a");
        list.add("a");
        list.get(1);
    }

    public int GetNumberOfK(int[] array, int k) {
        int l = 0, r = array.length - 1;
        int count = 0;
        while (l <= r) {
            if(l == r && array[l]!=k){
                break;
            }
            int mid = (l + r) >> 1;
            if (array[mid] == k) {
                int index = mid - 1;
                count++;
                while (index >= 0 && array[index] == k) {
                    count++;
                    index--;
                }
                index = mid + 1;
                while (index < array.length && array[index] == k) {
                    count++;
                    index++;
                }
                break;
            } else if (array[mid] > k) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        return count;
    }
}
